package com.yyl.fmall.user.shiro;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yyl.fmall.user.entity.User;
import com.yyl.fmall.user.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * @BelongsProject: rbacs
 * @BelongsPackage: com.yyl.rbacs.shiro
 * @Author: YuanSir
 * @CreateTime: 2022-11-3  14:16
 * @Description:
 * @Version: 1.0
 */

public class CustomRealm extends AuthorizingRealm {
    
    @Autowired
    private IUserService userService;
    
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    
        return null;
    }
    
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    
        String username = (String) token.getPrincipal();
    
        User dbUser = userService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username));
        
        if (dbUser == null){ //用户不存在
            
            throw new UnknownAccountException();
            
        }
    
        return new SimpleAuthenticationInfo(dbUser,
                dbUser.getPassword(),
                ByteSource.Util.bytes(dbUser.getSalt()),
                getName());
        
    }
    
}
